/**
 * 设备基础信息管理模块
 * 管理所有设备的基础信息，支持国际化
 */
const {
	deviceCollection,
	dbCmd
} = require('../../common/constants')
const {
	ERROR
} = require('../../common/error')
const {
	transformMultiLangData
} = require('../../lib/transform')

module.exports = {
	/**
	 * 检查设备是否存在，不存在则创建
	 * @param {object} params 设备参数
	 * @param {string} params.deviceId 设备ID
	 * @param {string} params.sn 设备SN码
	 * @param {string} params.firmwareVersion 固件版本
	 * @param {string} params.hardwareVersion 硬件版本
	 * @param {string} params.macAddress MAC地址
	 * @param {string} params.deviceType 设备类型
	 * @param {object} [params.deviceName] 设备名称（多语言）
	 * @returns {object} 设备信息
	 */
	async ensureDevice(params) {
		const { deviceId, sn, firmwareVersion, hardwareVersion, macAddress, deviceType, deviceName } = params
		
		if (!deviceId || !sn || !firmwareVersion || !hardwareVersion || !macAddress) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, sn, firmwareVersion, hardwareVersion, macAddress' }
			}
		}

		try {
			// 检查设备是否已存在
			const existingDevice = await deviceCollection.where({
				device_id: deviceId
			}).get()

			if (existingDevice.data.length > 0) {
				// 设备已存在，更新信息
				const device = existingDevice.data[0]
				const updateData = {
					firmware_version: firmwareVersion,
					hardware_version: hardwareVersion,
					mac_address: macAddress,
					last_seen: new Date(),
					update_time: new Date()
				}

				// 如果提供了设备名称，则更新
				if (deviceName) {
					updateData.device_name = deviceName
				}

				await deviceCollection.doc(device._id).update(updateData)
				
				return {
					...device,
					...updateData
				}
			} else {
				// 设备不存在，创建新设备
				const deviceData = {
					device_id: deviceId,
					sn,
					device_type: deviceType || 'pro',
					device_name: deviceName || {
						'zh-Hans': `沙画设备 ${sn}`,
						'en': `Sand Art Device ${sn}`,
						'ja': `サンドアート装置 ${sn}`,
						'ko': `샌드 아트 장치 ${sn}`,
						'es': `Dispositivo de Arte de Arena ${sn}`,
						'fr': `Appareil d'Art de Sable ${sn}`
					},
					firmware_version: firmwareVersion,
					hardware_version: hardwareVersion,
					mac_address: macAddress,
					status: 'offline',
					capabilities: {
						max_brightness: 100,
						min_brightness: 1,
						color_temperature_range: [2000, 6500],
						pattern_support: true,
						playlist_support: true,
						remote_control: true
					},
					first_seen: new Date(),
					last_seen: new Date(),
					create_time: new Date(),
					update_time: new Date()
				}

				const result = await deviceCollection.add(deviceData)
				
				return {
					_id: result.id,
					...deviceData
				}
			}
		} catch (error) {
			console.error('ensureDevice error:', error)
			throw error
		}
	},

	/**
	 * 更新设备状态
	 * @param {object} params 更新参数
	 * @param {string} params.deviceId 设备ID
	 * @param {string} params.status 设备状态
	 * @param {object} [params.additionalData] 额外数据
	 * @returns {object} 更新结果
	 */
	async updateDeviceStatus(params) {
		const { deviceId, status, additionalData } = params
		
		if (!deviceId || !status) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId, status' }
			}
		}

		try {
			const updateData = {
				status,
				last_seen: new Date(),
				update_time: new Date(),
				...additionalData
			}

			const result = await deviceCollection.where({
				device_id: deviceId
			}).update(updateData)

			if (result.updated === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND
				}
			}

			return {
				success: true,
				message: '设备状态更新成功'
			}
		} catch (error) {
			console.error('updateDeviceStatus error:', error)
			throw error
		}
	},

	/**
	 * 获取设备信息
	 * @param {object} params 查询参数
	 * @param {string} params.deviceId 设备ID
	 * @returns {object} 设备信息
	 */
	async getDevice(params) {
		const { deviceId } = params
		
		if (!deviceId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId' }
			}
		}

		try {
			const deviceResult = await deviceCollection.where({
				device_id: deviceId
			}).get()

			if (deviceResult.data.length === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND
				}
			}

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 转换数据格式
			const transformedData = transformMultiLangData(deviceResult.data, language, {
				multiLangFields: ['device_name'],
				keepFields: [
					'device_id', 'sn', 'device_type', 'firmware_version', 'hardware_version',
					'mac_address', 'status', 'capabilities', 'first_seen', 'last_seen',
					'create_time', 'update_time'
				],
				idMapping: { '_id': 'id' }
			})

			return transformedData[0]
		} catch (error) {
			console.error('getDevice error:', error)
			throw error
		}
	},

	/**
	 * 获取设备列表
	 * @param {object} params 查询参数
	 * @param {string} [params.status] 设备状态筛选
	 * @param {string} [params.deviceType] 设备类型筛选
	 * @param {number} [params.page=1] 页码
	 * @param {number} [params.limit=20] 每页数量
	 * @returns {object} 设备列表
	 */
	async getDeviceList(params = {}) {
		const { status, deviceType, page = 1, limit = 20 } = params

		try {
			// 构建查询条件
			let whereCondition = {}
			
			if (status) {
				whereCondition.status = status
			}
			
			if (deviceType) {
				whereCondition.device_type = deviceType
			}

			// 分页查询
			const skip = (page - 1) * limit
			const deviceResult = await deviceCollection
				.where(whereCondition)
				.orderBy('create_time', 'desc')
				.skip(skip)
				.limit(limit)
				.get()

			// 获取总数
			const countResult = await deviceCollection.where(whereCondition).count()

			// 获取当前请求的语言
			const language = this.language || 'zh-Hans'

			// 转换数据格式
			const transformedData = transformMultiLangData(deviceResult.data, language, {
				multiLangFields: ['device_name'],
				keepFields: [
					'device_id', 'sn', 'device_type', 'firmware_version', 'hardware_version',
					'mac_address', 'status', 'capabilities', 'first_seen', 'last_seen',
					'create_time', 'update_time'
				],
				idMapping: { '_id': 'id' }
			})

			return {
				list: transformedData,
				total: countResult.total,
				page,
				limit,
				totalPages: Math.ceil(countResult.total / limit)
			}
		} catch (error) {
			console.error('getDeviceList error:', error)
			throw error
		}
	},

	/**
	 * 删除设备
	 * @param {object} params 删除参数
	 * @param {string} params.deviceId 设备ID
	 * @returns {object} 删除结果
	 */
	async deleteDevice(params) {
		const { deviceId } = params
		
		if (!deviceId) {
			throw {
				errCode: ERROR.PARAM_REQUIRED,
				errMsgValue: { param: 'deviceId' }
			}
		}

		try {
			const result = await deviceCollection.where({
				device_id: deviceId
			}).remove()

			if (result.deleted === 0) {
				throw {
					errCode: ERROR.DEVICE_NOT_FOUND
				}
			}

			return {
				success: true,
				message: '设备删除成功'
			}
		} catch (error) {
			console.error('deleteDevice error:', error)
			throw error
		}
	}
}
